package geektime.spring.springbucks.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import geektime.spring.springbucks.mapper.CoffeeMapper;
import geektime.spring.springbucks.model.Coffee;
import geektime.spring.springbucks.model.CoffeeExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CoffeeService {
    private static final String CACHE = "springbucks-coffee";
    @Autowired
    private CoffeeMapper coffeeMapper;
    @Autowired
    private RedisTemplate<String, Coffee> redisTemplate;

    public PageInfo<Coffee> queryList(CoffeeExample example, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<Coffee> coffeeList = coffeeMapper.selectByExample(example);
        PageInfo<Coffee> pageInfo = new PageInfo<>(coffeeList);
        return pageInfo;
    }

    public Coffee queryById(Long id) {
        HashOperations<String, Long, Coffee> hashOperations = redisTemplate.opsForHash();
        if (redisTemplate.hasKey(CACHE) && hashOperations.hasKey(CACHE, id)) {
            log.info("Get coffee {} from Redis.", id);
            return hashOperations.get(CACHE, id);
        }
        Coffee coffee = coffeeMapper.selectByPrimaryKey(id);
        log.info("Coffee Found: {}", coffee);
        if (null != coffee) {
            log.info("Put coffee {} to Redis.", id);
            hashOperations.put(CACHE, id, coffee);
            redisTemplate.expire(CACHE, 1, TimeUnit.MINUTES);
        }
        return coffee;
    }

    @Transactional
    public void insert(Coffee coffee) {
        coffeeMapper.insert(coffee);
    }

    @Transactional
    public void update(Coffee coffee) {
        coffeeMapper.updateByPrimaryKeySelective(coffee);
    }

    @Transactional
    public void delete(Long id) {
        coffeeMapper.deleteByPrimaryKey(id);
    }

}
